package com.lottery.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lottery.server.entity.Prize;
import com.lottery.server.mapper.PrizeMapper;
import com.lottery.server.service.PrizeService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Random;

@Service
public class PrizeServiceImpl extends ServiceImpl<PrizeMapper, Prize> implements PrizeService {
    
    @Override
    @Transactional
    public Prize drawPrize() {
        // 获取所有还有库存的奖品
        LambdaQueryWrapper<Prize> wrapper = new LambdaQueryWrapper<>();
        wrapper.gt(Prize::getCount, 0);
        List<Prize> prizes = list(wrapper);
        
        if (prizes.isEmpty()) {
            return null;
        }
        
        // 计算总权重（所有奖品数量之和）
        int totalWeight = prizes.stream()
                .mapToInt(Prize::getCount)
                .sum();
        
        // 生成随机数
        Random random = new Random();
        int randomNumber = random.nextInt(totalWeight);
        
        // 根据权重选择奖品
        int currentWeight = 0;
        Prize selectedPrize = null;
        
        for (Prize prize : prizes) {
            currentWeight += prize.getCount();
            if (randomNumber < currentWeight) {
                selectedPrize = prize;
                break;
            }
        }
        
        // 减少奖品数量
        selectedPrize.setCount(selectedPrize.getCount() - 1);
        updateById(selectedPrize);
        
        return selectedPrize;
    }
} 